package cn.thornbird.orgsync.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Slf4j
public class EncryptUtil {

    public static final String MD5 = "MD5";

    public static final Charset UTF_8 = StandardCharsets.UTF_8;

    public static String csrfToken(HttpServletRequest request) {
        return md5(request.getSession().getId());
    }

    public static String generateGUID() {
        return UUID.randomUUID().toString().toUpperCase().replace("-", "");
    }

    public static String md5(String text) {
        String result = "";
        try {
            result = String.valueOf(text);
            MessageDigest messageDigest = MessageDigest.getInstance(MD5);
            result = bytesToHexString(messageDigest.digest(result.getBytes(UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            log.error("error", e);
        }
        return result;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (int i = 0, count = bytes.length; i < count; i++) {
            String value = Integer.toHexString(bytes[i] & 0xFF);
            result.append(value.length() == 1 ? "0" + value : value);
        }
        return result.toString();
    }

}
